<template>
    <div id="menu" class="row mt-3">
        <div class="col-sm-12 col-md-8">
            <h4>菜单</h4>
            <input class="form-control form-control-sm mb-1" type="text" placeholder="搜索披萨或拼音" autocomplete="off" v-model="search" />
            <table class="table">
                <thead class="thead-default">
                    <tr>
                        <th>英寸</th>
                        <th>价格</th>
                        <th>加入</th>
                    </tr>
                </thead>
                <tbody>
                    <template v-for="pizza in searchData">
                        <tr>
                            <th colspan="100%">{{pizza.name}}</th>
                        </tr>
                        <tr v-for="size in pizza.size">
                            <td>{{size.size}}英寸</td>
                            <td>￥{{size.price}}</td>
                            <td><button class="btn btn-sm btn-outline-success" @click="onCart(pizza.name, size)">+</button></td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
        <div class="col-sm-12 col-md-4">
            <h4>我的购物车</h4>
            <div v-if="getCarts.length">
                <table class="table">
                    <thead class="thead-default">
                        <tr>
                            <th>数量</th>
                            <th>品种</th>
                            <th>价格</th>
                            <th>总价</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="item in getCarts">
                            <td>
                                <button class="btn btn-sm" @click="operationCart(item.objectId, 'minus')">-</button>
                                <span>{{item.quantity}}</span>
                                <button class="btn btn-sm" @click="operationCart(item.objectId)">+</button>
                            </td>
                            <td>{{item.name}}{{item.size}}寸</td>
                            <td>{{item.price}}</td>
                            <td>{{item.totalPrice}}</td>
                        </tr>
                    </tbody>
                </table>
                <p>总计：￥{{getCarts.total}}</p>
                <button class="btn btn-success">提交</button>
                <button class="btn btn-danger foat-right" @click="onDeleteAll">清空购物车</button>
            </div>
            <div v-else class="shadow-sm p-3 mb-5 bg-white rounded">你的购物车空空如也~</div>
        </div>
        <div v-if="loading.show" id="loading">{{loading.message}}</div>
    </div>
</template>

<script>
    export default {
        name: "Menu",
        data() {
            return {
                limit: 5,
                data: [],
                search: "",
                cart: [],
                total: Number,
                loading: {show: false, message: "加载数据中..."}
            }
        },
        methods: {
            onCart(pizza, size) {
                const query = Bmob.Query("Cart");
                query.equalTo("name", "==", pizza);
                query.equalTo("size", "==", size.size);
                query.equalTo("userId", "==", this.getUser.objectId);
                query.find().then(response => {
                    if(response.length) {
                        const quantity = ++response[0].quantity;
                        query.set("id", response[0].objectId);
                        query.set("quantity", quantity);
                        query.set("totalPrice", quantity * response[0].price + ".00");
                        query.save().then(res => this.$store.commit("setCarts")).catch(error => console.log(error));
                    }else {
                        query.set("userId", {"__type": "Pointer", "className": "_User", "objectId": this.getUser.objectId});
                        query.set("name", pizza);
                        query.set("size", size.size);
                        query.set("price", size.price);
                        query.set("totalPrice", size.price);
                        query.save().then(res => this.$store.commit("setCarts")).catch(error => console.log(error));
                    }
                })
            },
            operationCart(id, operation) {
                const query = Bmob.Query("Cart");
                query.get(id).then(response => {
                    let quantity = response.quantity;
                    let price = parseInt(response.price);
                    if(operation == "minus") {
                        if(--quantity) {
                            query.set("id", id);
                            query.set("quantity", quantity);
                            query.set("totalPrice", quantity * price + ".00");
                            query.save().then(response => this.$store.commit("setCarts")).catch(error => console.log(error));
                        }else {
                            query.destroy(id).then(res => this.$store.commit("setCarts")).catch(error => console.log(error));
                        }
                    }else {
                        query.set("id", id);
                        query.set("quantity", ++quantity);
                        query.set("totalPrice", quantity * price + ".00");
                        query.save().then(response => this.$store.commit("setCarts")).catch(error => console.log(error));
                    }
                }).catch(error => console.log(error))
            },
            onDeleteAll() {
                const query = Bmob.Query("Cart");
                query.equalTo("userId", "==", this.getUser.objectId);
                query.limit(50);
                query.find().then(todos => todos.destroyAll().then(response => this.$store.commit("setCarts")).catch(error => console.log(error)));
            },
            handleScroll(event) {
                var bottom = window.scrollY + window.innerHeight;
                console.log(bottom, document.documentElement.offsetHeight)
                if(bottom == document.documentElement.offsetHeight) {
                    window.removeEventListener("scroll", this.handleScroll);
                    if(this.limit < this.getMenus.length) {
                        this.loading.show = true;
                        setTimeout(() => {
                            this.limit += 5;
                            this.loading.show = false;
                            window.addEventListener("scroll", this.handleScroll);
                        }, 1000);
                    }else {
                        this.loading.message = "已经到底啦...";
                        this.loading.show = true;
                        setTimeout(() => {
                            this.loading.show = false;
                            window.removeEventListener("scroll", this.handleScroll);
                        }, 1000);
                    }
                }
                event.returnValue = false;
            }
        },
        computed: {
            getMenus() {
                return this.$store.getters.getMenus;
            },
            getCarts() {
                return this.$store.getters.getCarts;
            },
            getUser() {
                return this.$store.getters.getUser;
            },
            searchData() {
                return this.getMenus.slice(0, this.limit).filter(item => item.name.match(this.search) || item.pinyin.match(this.search));
            },
        },
        created() {
            this.$store.commit("setMenus");
            this.$store.commit("setCarts");
            window.addEventListener("scroll", this.handleScroll);
        }
    }
</script>

<style scoped>
    button:focus {box-shadow: none;}
    td {white-space: nowrap;}
    #loading {color: #999;margin: 0 auto;}
</style>